/*
 * Copyright © 2011 by PropSage Pte Ltd. 
 * All Rights Reserved.
 * licensing@propsage.com
 * http://www.propsage.com/terms.html
 * 
 * 
 * Javascript for /case/index
 * 
 * @author Poh Nean
 */
propsage.namespace("prestige.invoice");


prestige.invoice.update = (function($, ui) {

	var row;
	var selectedTrans = [];

	function initComponents()
	{
		$("#chooseTransactionsDlg tr:odd").addClass("odd");
		$("#chooseTransactionsDlg").dialog({
			'width': 700,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel,
				'OK': {
					'text': 'OK',
					'class': 'blue',
					'click': onChooseTransactionOK
				}
			},
			'open': onChooseTransactionOpen
		});
		$("#choosePartyDlg").dialog({
			'width': 900,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel
			},
			'open': onChoosePartyOpen
		});
		$('#invoice-items input[name*="property_case_id"]').each(function(index) {
			var transId = $(this).val();
			setSelectedTransaction(transId);
		});

		if (propCaseIdForNewInvoice !== null) {
			var $row = $('#invoice-items table.form-table tbody:first tr');
			var amount = Number($row.find('td.item-amount input').val());
			var gstAmount = Number($row.find('td.gst-amount input:text').val());
			if (gstAmount > 0) {
				$row.find('td.gst-amount input:checkbox').prop('checked', true);
			}
			$('#subtotal td').text(currency_code + ' ' + amount.toFixed(2));
			$('#grandTotal td').text(currency_code + ' ' + amount.toFixed(2));

		}

		$("#tabs").tabs();

		$("#AddContactDlg").dialog({
			'width': 500,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel,
				'OK': {
					'text': 'Add Contact',
					'class': 'blue',
					'click': onAddContactOK
				}
			},
			'open': onAddContactOpen
		});

		$("#EditContactDlg").dialog({
			'width': 650,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel,
				'OK': {
					'text': 'Update Contact',
					'class': 'blue',
					'click': onEditContactOK
				}
			},
			'open': onEditContactOpen
		});

		$('#btnChooseParty').PsSearchBillableParty({
			'clearButton': '#btnClearAgent',
			'fields': {
				'party_id': '#Invoice_to_party_id',
				'name': '#Invoice_bill_to_name',
				'address': '#Invoice_bill_to_address',
				'model': '#model'
			}
		});

		removeEmptyTransactionHeaders();
		
		if(propertyCaseBillto) {
			var n = propertyCaseBillto.search("Solicitor");
			if(n>0) {
				$('#editCareOf').show();
				$('#invoice-care-of').hide();
			}
		}

	}

	function removeEmptyTransactionHeaders()
	{
		$('#select-transaction-grid table.items thead tr.filters td:gt(3)').each(function() {
			$(this).remove();
		})
	}

	function setSelectedTransaction(propCaseId) {
		selectedTrans.push(propCaseId);
		$('#chooseTransactionsDlg input:radio[value="' + propCaseId + '"]').attr('disabled', true).closest('tr').addClass('trans-selected');
	}

	function unsetSelectedTransaction(propCaseId) {
		selectedTrans.splice($.inArray(propCaseId, selectedTrans), 1);
		$('#chooseTransactionsDlg input:radio[value="' + propCaseId + '"]').attr('disabled', false).closest('tr').removeClass('trans-selected');
	}

	function initEventHandlers() {

		$('#Invoice_terms_select').live('change', function() {
			var val = $(this).val();

			if (val == 'Other') {
				$('#Invoice_terms').show().val('');
			} else {
				$('#Invoice_terms').hide().val(val);
			}
		});

		$('#invoice-items tbody.inactive input, #invoice-items tbody.inactive textarea').live('focus', function() {
			$(this).closest('tbody').removeClass('inactive');
		});

		$('#invoice-items tbody:not(.inactive) input, #invoice-items tbody:not(.inactive) textarea').live('keydown', function() {
			var $this = $(this);
			setTimeout(function() {
				var val = $this.val();

				if (val != '' && $this.closest('tbody').is(':last-child')) {
					addRow($this);
				}
			});
		});

		$('#btnAddInvoiceItem').click(function(event) {
			event.preventDefault();
			addRow();
		});

		$('#invoice-items .remove-invoice-item').live('click', function(event) {
			event.preventDefault();
			removeRow(this);
		});

		$('#invoice-items').delegate('td.qty input', 'change', onQuantityChange);
		$('#invoice-items').delegate('td.unit-price input', 'change', onUnitPriceChange);
		$('#invoice-items').delegate('td.item-amount input', 'change', onItemAmountChange);
		$('#invoice-items').delegate('td.gst-amount input[type=checkbox]', 'change', onItemTaxableChange);

		$('#btnFinish').click(onSubmitClick);

		$('.btnChooseTransaction').click(function() {
			row = $(this).attr('rowId');
			var assignedPropCaseId = $(this).closest('td').find('input[name*="property_case_id"]').val();
			$('#chooseTransactionsDlg input:radio[value="' + assignedPropCaseId + '"]').attr('checked', true);
			$("#chooseTransactionsDlg").dialog("open");
		});

		//		$('#btnChooseParty').click(function() {
		//			$("#choosePartyDlg").dialog("open");
		//		});


		$('#PropertyCaseInvoice_property_case_id').change(onPropertyCaseIdChange);
		$('#btAddContact').click(function() {
			$("#AddContactDlg").dialog("open");
		});
		$('#btnEditContact').click(onBtnEditContactClick);

		$('a.selectParty').live('click', onGridViewPartySelect);

		$('#bill_to_0').on('click', onExistingCheckBoxClicked);
		$('#bill_to_1').on('click', onNewCheckBoxClicked);

		$('#tabs ul li a').click(onTabHeaderClick);

		$('#btnClearParty').click(onClearAllClick);
		
		$('a#invoice-care-of').click(onAddInvoiceCareofClick);
		$('a#invoice-attn').click(onAddInvoiceAttnClick);

	}

	function onClearAllClick() {
		$('#billToDetails').hide();
		$('#editContactRow').hide();
		$('#searchOrAdd').show();
		$('#bill_to_0').attr('checked', 'checked');
		$('#btnChooseParty').show();
		$('#clearAll').hide();
	}

	function onTabHeaderClick() {
		$('#tabs ul li a').removeClass('active');
		$(this).addClass('active');
	}



	function onBtnEditContactClick()
	{
		var href = '';
		var data = {};

		var toPartyId = $('#Invoice_to_party_id').val();
		var model = $('#model').val();
		if (model == 'Contact') {
			href = baseUrl + '/contact/default/ajaxGetContactDetails';
			data = {
				'party_id': toPartyId
			};
			ui.doAjax('post', href, data, onGetContactDetailsSuccess);
			$("#EditContactDlg").dialog("open");
			if ($("#Contact_id").val() == "") {
				$("#Contact_id").val($("#Invoice_contact_id").val());
			}
		} else {

		}

	}


	function onExistingCheckBoxClicked() {
		$('#toNew').hide();
		$('#billToDetails').hide();
		$('#editContactRow').hide();
		$('#clearAll').hide();
		$('#toExisting').show();
		$('#btnChooseParty').show();
	}

	function onNewCheckBoxClicked() {
		$('#toExisting').hide();
		$('#billToDetails').hide();
		$('#editContactRow').hide();
		$('#clearAll').hide();
		$('#toNew').show();
	}


	function onGridViewPartySelect() {
		var type = $(this).attr('type');
		var typeLabel = type;
		if (type == 'User') {
			typeLabel = 'Agent';
		}
		var result = confirm('Bill this ' + typeLabel + '?');
		if (!result) {
			return false;
		}

		var href = '';
		var data = {};


		var id = $(this).closest('tr').find('td.id').text();
		var party_id = $(this).closest('tr').find('td.party_id').text();
		var name = $(this).closest('tr').find('td.name').text();

		if (party_id.trim() === "" || !$.isNumeric(party_id) || Math.floor(party_id) != party_id) {
			href = baseUrl + '/invoice/ajaxGetPartyId';
			data = {
				'id': id,
				'model': type
			};
			ui.doAjax('post', href, data, onGetPartyIdSuccess);
		} else {
			$('#Invoice_to_party_id').val(party_id);
		}

		if (type == "Contact") {
			href = baseUrl + '/contact/default/ajaxGetContactDetails';
			data = {
				'id': id
			};
			ui.doAjax('post', href, data, onGetContactDetailsSuccess);
		}

		$('#choosePartyDlg').dialog("close");
		$('tr.bill-to-info').show();

		$('#Invoice_bill_to_name').val(name);
		$('#billToName').html(name);

		var withAddress = ["Contact", "Agency"];
		if ($.inArray(type, withAddress) > -1) {
			var address = $(this).closest('tr').find('td.address').text();
			updateAddress(address);
			//			$('#clearAll').show();
		}
	}

	function updateAddress(address) {
		if (address.trim() === "") {
			$('#Invoice_bill_to_address').val('');
			$('#billToAddress').html('Address not found. Please enter billing address.');
		} else {
			var addressDisplayed = address.split(', ').join('<br/>');
			addressDisplayed = address.split(',').join('<br/>');
			$('#Invoice_bill_to_address').val(address);
			$('#billToAddress').html(addressDisplayed);
		}
	}

	function onGetPartyIdSuccess(response) {
		if (response.result == 'success') {
			$('#Invoice_to_party_id').val(response.party_id);
		} else {

		}
	}

	function onGetContactDetailsSuccess(response) {
		if (response.result == 'success') {
			$.each(response, function(key, value) {
				if ($('#edit-contact-form #Contact_' + key).length > 0) {
					$("#edit-contact-form #Contact_" + key).val(value);
				}
			});
		} else {

		}
	}


	function onItemTaxableChange() {
		var $row = $(this).closest('tr');

		var unitPrice = $row.find('.unit-price input').autoNumeric('get');
		var qty = $row.find('.qty input').autoNumeric('get');
		var unitTotal = unitPrice * qty;

		var isTaxable = $(this).is(':checked');
		var $gstAmountInput = $(this).closest('td').find('input[type=text]');

		if (isTaxable) {
			var gstAmount = gstRate * unitTotal;

			$gstAmountInput.autoNumeric('set', gstAmount);
		} else {
			$gstAmountInput.autoNumeric('set', 0);
		}

		updateItemTotals($row);
	}

	function onQuantityChange(event) {
		var $row = $(this).closest('tr');
		updateItemTotals($row);
	}

	function onUnitPriceChange(event) {
		var $row = $(this).closest('tr');
		updateItemTotals($row);
	}

	function onItemAmountChange(event) {
		var $row = $(this).closest('tr');
		updateItemAmountPrice($row);
	}

	function onTaxSelected() {
		var $row = $(this).closest('tr');
		updateItemTotals($row);
	}

	function updateItemTotals($row) {
		var $quantityInput = $row.find('.qty input');
		var $unitPriceInput = $row.find('.unit-price input');
		var $isTaxableInput = $row.find('.gst-amount input[type=checkbox]');
		var $gstAmountInput = $row.find('.gst-amount input[type=text]');
		//		var $taxesSelect = $row.find('td.tax-id select');

		var isTaxable = $isTaxableInput.is(':checked');
		var quantity = $quantityInput.autoNumeric('get');
		var unitPrice = $unitPriceInput.autoNumeric('get');

		if (!isNaN(quantity) && !isNaN(unitPrice)) {
			var gstAmount = 0;
			if (isTaxable) {
				gstAmount = (quantity * unitPrice) * (gstRate);
			}
			var amount = (quantity * unitPrice) + gstAmount;

			$gstAmountInput.autoNumeric('set', gstAmount);
			$row.find('.item-amount input').autoNumeric('set', amount);

		} else {
			$row.find('.item-amount input').val("");
		}

		updateTotals();
	}

	function updateItemAmountPrice($row) {
		var $quantityInput = $row.find('.qty input');
		var $unitPriceInput = $row.find('.unit-price input');
		var $itemAmountPriceInput = $row.find('.item-amount input');
		var $isTaxableInput = $row.find('.gst-amount input[type=checkbox]');
		var $gstAmountInput = $row.find('.gst-amount input[type=text]');
		//		var $taxesSelect = $row.find('td.tax-id select');

		var isTaxable = $isTaxableInput.is(':checked');
		var quantity = $quantityInput.autoNumeric('get');
		var amount = $itemAmountPriceInput.autoNumeric('get');
		var unitPrice = 0;
		var gstAmount = 0;

		if (!isNaN(amount)) {
			gstAmount = 0;
			unitPrice = 0;
				
			if (isTaxable) {
				//assume quantity is 1
				gstAmount = (amount * gstRate) / (1 + gstRate);
				unitPrice = amount / (1 + gstRate);
			} else {
				unitPrice = amount;
			}

			$gstAmountInput.autoNumeric('set', gstAmount);
			$unitPriceInput.autoNumeric('set', unitPrice);
		} else {
			$row.find('.unit-price input').val("");
		}
		updateTotals();
	}

	function updateTotals() {
		var subTotal = getSubTotal();

		var grandTotal = getGrandTotal();

		$('#subtotal td').text(currency_code + ' ' + subTotal.toFixed(2));
		$('#grandTotal td').text(currency_code + ' ' + grandTotal.toFixed(2));
	}

	function getSubTotal() {
		var subTotal = 0, grandTotal = 0, itemTotal = 0, quantity, unitPrice, $quantityInput, $unitPriceInput;

		var $tbodys = $('#invoice-items tbody').not('.inactive');

		$tbodys.find('.item-amount input').each(function(i) {
			itemTotal = $(this).autoNumeric('get');
			subTotal += Number(itemTotal);
		});

		return subTotal;
	}

	function getGrandTotal() {
		// TODO
		return getSubTotal();
	}

	function addRow() {
		var $tbody = $('#invoice-items tbody:last-child');
		var $selectAccount = $('#invoice-items tbody:last-child td.account-id div.account-select');
		var $taxSelect = $('#invoice-items tbody:last-child td.gst-amount div.tax-select select');
		var $selectTransBtn = $('#invoice-items tbody:last-child td img.btnChooseTransaction');
		var $propCaseIdField = $('#invoice-items tbody:last-child td input[name*="property_case_id"]');

		var lastRowId = $selectTransBtn.attr('rowId');
		var nextRowId = parseInt(lastRowId) + 1;
		var count = $('#invoice-items tbody').size();
		var rowNum = count;

		var append = '<tbody class="inactive"><tr>'
				+ '<td><textarea rows="4" placeholder="" name="InvoiceItem[' + rowNum + '][description]" id="InvoiceItem_' + rowNum + '_description" /> <div class="errorMessage" id="InvoiceItem_' + rowNum + '_description_em_" style="display:none"></div></td>'
				+ '<td class="qty"><div class="form-block "><input class="" placeholder="" size="20" id="InvoiceItem_' + rowNum + '_quantity" name="InvoiceItem[' + rowNum + '][quantity]" maxlength="20" type="text"><div class="errorMessage" id="InvoiceItem_' + rowNum + '_quantity_em_" style="display:none"></div></div></td>'
				+ '<td class="unit-price"><div class="form-block "><input class="" placeholder="" size="20" id="InvoiceItem_' + rowNum + '_unit_price" name="InvoiceItem[' + rowNum + '][unit_price]" maxlength="20" type="text"><div class="errorMessage" id="InvoiceItem_' + rowNum + '_unit_price_em_" style="display:none"></div></div></td>'
				+ '<td class="account-id"></td>'
				+ '<td class="gst-amount"><div class="form-block "><input type="hidden" name="InvoiceItem[' + rowNum + '][is_taxable]" value="0" id="ytInvoiceItem_' + rowNum + '_is_taxable"><input type="checkbox" value="1" id="InvoiceItem_' + rowNum + '_is_taxable" name="InvoiceItem[' + rowNum + '][is_taxable]"><input class="" size="5" id="InvoiceItem_' + rowNum + '_gst_amount" name="InvoiceItem[' + rowNum + '][gst_amount]" maxlength="5" type="text"><div class="errorMessage" id="InvoiceItem_' + rowNum + '_gst_amount_em_" style="display:none"></div></div></td>'
				+ '<td class="item-amount"><div class="form-block "><input class=""  size="20" id="InvoiceItem_' + rowNum + '_amount" name="InvoiceItem[' + rowNum + '][amount]" maxlength="20" type="text"><div class="errorMessage" id="InvoiceItem_' + rowNum + '_amount_em_" style="display:none"></div></div></td>'
				+ '<td class="remove-invoice-item-column"><a href="javascript:void(0);" tabindex="-1" class="remove-invoice-item blue link"><img src="/images/icons/fugue/cross-button.png" width="16" height="16" /></a></td>'
				+ '</tr></tbody>';

		$tbody.after(append);

		$selectAccount.clone(true).appendTo('#invoice-items tbody:last-child td.account-id');
		$selectTransBtn.clone(true).attr('rowId', nextRowId).appendTo('#invoice-items tbody:last-child td:first');
		$propCaseIdField.clone(true).val('').attr('id', 'InvoiceItem_' + nextRowId + '_property_case_id').attr('name', 'InvoiceItem[' + nextRowId + '][property_case_id]').appendTo('#invoice-items tbody:last-child td:first');



		//		var $newTaxSelect = $taxSelect.clone();
		//		$newTaxSelect.appendTo('#invoice-items tbody:last-child td.tax-id div.tax-select');

		$('#InvoiceItem_' + rowNum + '_quantity')
				.val('1.00')
				.autoNumeric({
			'vMax': '9999999.99'
		});

		$('#InvoiceItem_' + rowNum + '_unit_price')
				.autoNumeric();

		$('#InvoiceItem_' + rowNum + '_gst_amount')
				.autoNumeric();

		$('#InvoiceItem_' + rowNum + '_amount')
				.autoNumeric({
			'aSign': currency_code + ' '
		});

		if (count >= 1) {
			$('#invoice-items').find('tbody .remove-invoice-item').show();
		}
	}

	function removeRow(currentRow) {
		var tbody = $(currentRow).closest('tbody');
		var assignedPropCaseId = tbody.find('input[name*="property_case_id"]').val();
		if (assignedPropCaseId) {
			unsetSelectedTransaction(assignedPropCaseId);
		}
		tbody.remove();

		var count = $('#invoice-items').find('tbody').length;

		if (count <= 1) {
			$('#invoice-items').find('tbody').removeClass('inactive');
			$('#invoice-items').find('tbody .remove-invoice-item').hide();
		}
		updateTotals()
	}

	function onSubmitClick(event) {
		var val;

		if ($('#searchOrAdd').is(":visible")) {
			alert('You have not selected a party to invoice.');
			$('#btnChooseParty').focus();
			return false;
		}

		$('#update-invoice-form #invoice-items tbody.inactive').remove();

		// do validation
		var hasErrors = false;
		$('tbody').not('.inactive').find('[id^=InvoiceItem]').filter('input[type=text], textarea').each(function() {
			val = $(this).val();
			var id = $(this).attr('id');

			$('#' + id + '_em_').hide();

			if (val == '') {
				var name = $(this).attr('name');

				var regex = /InvoiceItem\[\d+\]\[(.*)\]/gi;
				var type = regex.exec(name)[1];

				if (type == 'description') {
					type = 'Description';
				} else if (type == 'amount') {
					type = 'Amount';
				} else if (type == 'unit_price') {
					type = 'Unit Price';
				} else if (type == 'quantity') {
					type = 'Quantity';
				}

				$('#' + id + '_em_').text(type + ' cannot be empty').show();
				hasErrors = true;
			}
		});

		$('td.item-amount input').each(function(i) {
			var amount = $(this).autoNumeric('get');
			this.disabled = false;
			$(this).val(amount);
		})

		$('td.unit-price input, td.gst-amount input:text').each(function(i) {
			var amount = $(this).autoNumeric('get');
			$(this).val(amount);
		})


		return !hasErrors;
	}


	function onPropertyCaseIdChange(event) {
	}

	function onPartySelected(event, ui) {
		$('#Invoice_to_party_id').val('');
		if (ui.item.party_id) {
			$('#Invoice_to_party_id').val(ui.item.party_id);
		}
		if (ui.item.label) {
			$('#Invoice_bill_to_name').val(ui.item.label);
		}
		$('#billToAddress').html('');
		$('#add-contact-form input').val('');
		$('#Invoice_bill_to_address').val('');
		if (ui.item.address) {
			var addressDisplayed = ui.item.address;
			addressDisplayed = addressDisplayed.split('\n').join('<br/>');

			$('#edit-contact-form #Contact_id').val(ui.item.id);
			$('#edit-contact-form #Contact_name').val(ui.item.label);
			$('#edit-contact-form #Contact_postcode').val(ui.item.postcode);
			$('#edit-contact-form #Contact_building').val(ui.item.building);
			$('#edit-contact-form #Contact_block').val(ui.item.block);
			$('#edit-contact-form #Contact_street').val(ui.item.street);
			$('#edit-contact-form #Contact_floor').val(ui.item.floor);
			$('#edit-contact-form #Contact_unit').val(ui.item.unit);
			$('#edit-contact-form #Contact_country_code').val(ui.item.country_code);

			$('#billToAddress').html(addressDisplayed);
			$('#Invoice_bill_to_address').val(ui.item.address);

			$('#editContactRow').show();
		}
		$('#Invoice_contact_id').val('');
		if (ui.item.category == 'Contacts' && ui.item.id) {
			$('#Invoice_contact_id').val(ui.item.id);
		}

	}

	function onChooseTransactionOpen() {

	}

	function onChoosePartyOpen() {

	}

	function onChooseTransactionOK() {
		var currentPropertyCaseId = $('img[rowId="' + row + '"]').closest('td').find('input[name*="property_case_id"]').val();
		var newPropertyCaseId = $('#chooseTransactionsDlg input[type="radio"]:checked').val();
		setSelectedTransaction(newPropertyCaseId);
		if (currentPropertyCaseId != newPropertyCaseId) {
			unsetSelectedTransaction(currentPropertyCaseId);
		}

		var $dataRow = $('#chooseTransactionsDlg input[type="radio"]:checked').closest('tr');

		var property = $dataRow.find('td.trans-prop').text();
		property = property.split(', ').join('\n');
		property = property.split(',').join('\n');

		var type = $dataRow.find('td.trans-type').text();
		if (type.indexOf('Lease') != -1) {
			type = 'Lease';
		}
		var string = 'Being brokerage commission for the ' + type + ' of: \n' + property;
		var earnedComm = $dataRow.find('td.trans-comm').text();
		var gstAmount = $dataRow.find('td.trans-gst-amount').text();
		var isTaxable = $dataRow.find('td.trans-gst-payable').text() == '1' ? true : false;

		$('img[rowId="' + row + '"]').closest('td').find('input[name*="property_case_id"]').val(newPropertyCaseId);
		$('img[rowId="' + row + '"]').closest('td').find('textarea').html(string);

		var $row = $('img[rowId="' + row + '"]').closest('tr');
		var invoiceItemsCount = $('#invoice-items tbody:not(.inactive)').length;

		$row.find('td input[id="InvoiceItem_' + row + '_unit_price"]').autoNumeric('set', earnedComm);
		$row.find('td input[id="InvoiceItem_' + row + '_gst_amount"]').autoNumeric('set', gstAmount);
		$row.find('td input[id="InvoiceItem_' + row + '_is_taxable"]').prop('checked', isTaxable);

		$row.closest('tbody').removeClass('inactive');
		updateItemTotals($row);


		$('#chooseTransactionsDlg').dialog('close');

	}

	function onDialogCancel() {
		$(this).dialog("close");
	}

	function onAddContactOpen() {
		$(this).find('#btnSearchPostalcodeContact').PsSearchPostcode({
			'fields': {
				'postcode': '#AddContactDlg #Contact_postcode',
				'block': '#AddContactDlg #Contact_block',
				'street': '#AddContactDlg #Contact_street',
				'building_name': '#AddContactDlg #Contact_building',
				'district': '#AddContactDlg #Contact_district',
				'country_code': '#AddContactDlg #Contact_country_code'
			}
		});
		$('#AddContactDlg').find("input[id*=Contact_]").each(function(index) {
			$(this).val('');
		});
	}

	function onEditContactOpen() {
		$(this).find('#btnSearchPostalcodeContact').PsSearchPostcode({
			'fields': {
				'postcode': '#EditContactDlg #Contact_postcode',
				'block': '#EditContactDlg #Contact_block',
				'street': '#EditContactDlg #Contact_street',
				'building_name': '#EditContactDlg #Contact_building',
				'district': '#EditContactDlg #Contact_district',
				'country_code': '#EditContactDlg #Contact_country_code'
			}
		});
	}

	function onAddContactOK() {
		var isValid = false,
				data = null,
				href = null,
				invoiceId = null;

		isValid = $('#add-contact-form').yiiactiveform2("validate");

		if (isValid) {
			data = $("#add-contact-form").serializeArray();
			//			href = $("#add-contact-form").attr("action");
			invoiceId = $('#Invoice_id').val();
			if (invoiceId) {
				href = baseUrl + '/contact/default/ajaxAddContact?invoice_id=' + invoiceId;
			} else {
				href = baseUrl + '/contact/default/ajaxAddContact/';
			}

			ui.growl('Saving...', 'loading');
			ui.doAjax('post', href, data, onAddContactSuccess);
			$('#AddContactDlg').dialog("close");
			if (invoiceId) {
				$('#Invoice_to_party_id').val('');
			}
		}
	}

	function onEditContactOK() {
		var isValid = false,
				data = null,
				href = null;

		var contactId = $('#Contact_id').val();
		var invoiceId = $('#Invoice_id').val();
		console.log(baseUrl);
		isValid = $('#edit-contact-form').yiiactiveform2("validate");

		if (isValid) {
			data = $("#edit-contact-form").serializeArray();
			href = baseUrl + '/contact/default/ajaxUpdateContact/' + contactId + '?invoice_id=' + invoiceId;
			ui.growl('Updating...', 'loading');
			ui.doAjax('post', href, data, onEditContactSuccess);
			$('#EditContactDlg').dialog("close");
		}
	}

	function onDialogCancel() {
		$(this).dialog("close");
	}

	function onAddContactSuccess(response) {
		ui.growl('Contact added.');
		if (response['name'] !== null) {
			$("#Invoice_bill_to_name").val("");
			var address = response.addressFormatted;
			address = address.split(', ').join('\n');
			address = address.split(',').join('\n');
			var addressDisplayed = response.addressFormatted;
			addressDisplayed = addressDisplayed.split(', ').join('<br/>');
			addressDisplayed = addressDisplayed.split(',').join('<br/>');
			$('#billToAddress').show();
			$('#btnEditContact').show();
			$('#model').val('Contact');
			$("#billToAddress").html(addressDisplayed);
			$("#Invoice_bill_to_name").val(response['name']);
			$("#Invoice_bill_to_address").text(address);
			$("#Invoice_bill_to_address").hide();
			$("#Invoice_contact_id").val(response['id']);
			$("#Invoice_to_party_id").val(response['party_id']);

			$.each(response, function(key, value) {
				if ($('#edit-contact-form #Contact_' + key).length > 0) {
					$('#Contact_' + key).val(value);
				}
			})

			$('#searchOrAdd').hide();
			$('tr.bill-to-info').show();
			$('#clearAll').show();

		}
		$('#add-contact-form input').val('');
	}

	function onEditContactSuccess(response) {
		ui.growl('Contact updated.');
		if (response['name'] !== null) {
			var address = response.addressFormatted;

			address = address.split(', ').join('\n');
			address = address.split(',').join('\n');

			$("#Invoice_bill_to_address").text(address);
			$("#Invoice_bill_to_address").val(address);
			$("#Invoice_contact_id").val(response['id']);

			var addressDisplayed = response.addressFormatted;
			addressDisplayed = addressDisplayed.split(', ').join('<br/>');
			addressDisplayed = addressDisplayed.split(',').join('<br/>');

			$("#billToAddress").html(addressDisplayed);

			$('#searchOrAdd').hide();
			$('#clearAll').show();
		}
	}

	function onPropertyCaseIdChange(event) {
		var id = $('#PropertyCaseInvoice_property_case_id').val();

		if (id > 0) {
			window.location.href = baseUrl + '/invoice/create?id=' + id;
		} else {
			window.location.href = baseUrl + '/invoice/create';
		}
	}
	
	function onAddInvoiceCareofClick(event) {
		var $this = $(this);
		
		$('#editCareOf').show();
		$this.hide();
	}
	
	function onAddInvoiceAttnClick(event) {
		var $this = $(this);
		
		$('#editAttn').show();
		$this.hide();
	}
	
	$(document).ready(function(){
		if(($('#newInvoice').val() == 1 && $('#propertyCaseBillToPartyId').val() !== '') || $('#newInvoice').val() == 0){
			$('#bill_to_0').prop('checked', 'true');
			$('#searchOrAdd').hide();

			if ($('#model').val() != 'Contact') {
				$('#billToDetails').show();
				$('#Invoice_bill_to_name').show();
				$('#billToAddress').hide();
				$('#btnEditContact').hide();
				$('#editContactRow').show();
				$('#Invoice_bill_to_address').show();
			} else {
				$('#billToDetails').show();
				$('#Invoice_bill_to_name').show();
				$('#editContactRow').show();
				$('#billToAddress').show();
				$('#btnEditContact').show();
				$('#Invoice_bill_to_address').hide();
				//			$('#btnEditContact').trigger('click');
			}
			$('#clearAll').show();
		}


		initComponents();
		initEventHandlers();
	});

	return {
		onPartySelected: onPartySelected,
		removeEmptyTransactionHeaders: removeEmptyTransactionHeaders
	}

}(jQuery, propsage.ui));